#include<stdio.h>
#include<stdlib.h>
#include<math.h>

typedef struct 
{
	int n;
	int x;
}score_st;

typedef struct ployomial_st
{
	score_st data;
	struct ployomial_st *next;
}node;



	int list_create(node **me)
{
	*me = malloc(sizeof(**me));
		if(*me == NULL)
			return -1;
		return 0;
}

	int list_insert(node *me,score_st *data)
{
	node *p = me,*new;
	while(p->next && p->next->data.x < data->x)
	{
		p = p->next;

	}
	new = malloc(sizeof(*new));
		if(new == NULL)
			return -1;
		new->data = *data;
		new->next = p->next;
		p->next = new;
		return 0;
}

	int list_show(node *me)
{
	node *p;
	if(me == NULL)
		return -1;
	for(p = me->next;p != NULL;p = p->next)
		printf("%d %d\n",p->data.n,p->data.x);
		printf("\n");
}

	void list_distory(node *me)
{
	node *p,*next;
	for(p = me->next;p != NULL;p = next)
	{
		next = p->next;
		free(p);
	}
	free(me);
}

	void list_remove(node *me)
{

	node *q = me;
	node *temp = NULL;
	node *flag = NULL;
	
	for(;q->next != NULL;q = q->next)
	{
		for(temp = q->next;temp->next && q->next->data.x == temp->next->data.x;)
		{
			q->next->data.n += temp->next->data.n;
			if(temp->next)
			{
				flag = malloc(sizeof(*flag));
				flag = temp->next;
				temp->next = flag->next;
				free(flag);
			}
		}
	}
}
	
	void list_union(node *me,node *me1)
{
	node *p = me->next;
	node *q = me1->next;
	node *r = me;

	while(p && q)
	{
		if(p->data.x < q->data.x)
		{
			r->next = p;
		        r = p;
			p = p->next;	
		}
			else if(p->data.x > q->data.x)
			{
				r->next = q;
				r = q;
				q = q->next;
			}
				else
				{
					p->data.n += q->data.n;
					if(p->data.n)
					{
						r->next = p;
						r = p;
					}
					p = p->next;
					q = q->next;
				}
		if(p == NULL)
			r->next = q;
		else
			r->next = p;
	}	
}

	int main()
{
	int i,k;
	node *list = NULL;
	node *list1 = NULL;

	list_create(&list);
	list_create(&list1);
	
	score_st ploy,ploy1;
	for(i = 0;i < 5;i++)
	{
	ploy.n = rand()%2;
	ploy.x = pow(2,(rand()%4));
	list_insert(list,&ploy);
	}
	
	for(i = 0;i < 7;i++)
	{
	ploy1.n = rand()%4;
	ploy1.x = pow(2,(rand()%7));
	list_insert(list1,&ploy1);
	}

	list_remove(list);
	list_remove(list1);
	list_show(list);
	list_show(list1);

	list_union(list,list1);
	list_show(list);

	list_distory(list);
//	list_distory(list1);

	exit(0);
}
